/*
 * Copyright 2012 LIG SIGMA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.lig.sigma.astral.operators;

import fr.lig.sigma.astral.common.event.EventProcessor;
import fr.lig.sigma.astral.common.event.EventScheduler;
import fr.lig.sigma.astral.common.event.SchedulerContainer;
import fr.lig.sigma.astral.common.structure.Entity;

/**
 * @author Loic Petit
 */
public class InputManager {
    private Operator output;

    public InputManager(Operator output) {
        this.output = output;
        inputsArray = new Entity[output.getMaxInputs()];

    }

    protected EventProcessor[] waitList = EventProcessor.NO_WAIT;

    public EventProcessor[] waitFor() {
        return inputsArray.length == 0 ? waitList : inputsArray;
    }

    private int inputId = 0;
    private Entity[] inputsArray;

    public Entity[] getInputs() {
        return inputsArray;
    }

    protected void addInput(Entity in, boolean beNotifier) {
        inputsArray[inputId++] = in;
        if (beNotifier)
            in.registerNotifier(output);
    }

    public EventScheduler getScheduler() {
        if (inputsArray.length == 0)
            throw new IllegalStateException("Fatal: No scheduler implied in this operator as there was no input");
        EventProcessor p = inputsArray[0];
        if (p instanceof SchedulerContainer)
            return ((SchedulerContainer) p).getScheduler();
        throw new IllegalStateException("Fatal: This operator has as input something that is neither a source nor an operator "+p);
    }

}
